import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import { getQiniuToken, uploadQiniu } from "../api/api";

export default new Vuex.Store({
  state: {
    uid: "",
    token: "",
    userInfo: {},
    isLogin: false,
    num:{},
    UserDetail:{}
  },
  // 追踪
  getters: {},
  // 修改数据
  mutations: {
    // opens(state,val){
    //   state.a =val
    // }
    exist(state, [key, val]) {
      state[key] = val;
    },
    clear(state) {
      state["uid"] = "";
      state["token"] = "";
      state["userInfo"] = {};
      state["isLogin"] = false;
    },
  },
  // 异步的
  actions: {
    // 上传图片
    async upload(o, uploader) {
      // 接受upload  [file]组成的数组
      if (!Array.isArray(uploader) || uploader.length === 0) {
        return [];
      }
      console.log(uploader)

      let task = uploader.map((v) => {
        return new Promise((resolve) => {
          let file = v.file;
          // 生成一个随机名字
          let { type } = file;
          type = type.split("/")[1];

          // 重新命名
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;

          getQiniuToken().then((res) => {
            const formdata = new FormData();
            formdata.append("file", file);
            formdata.append("token", res.data.token);
            formdata.append("key", file_name);

            // 上传到七牛云的服务器了
            uploadQiniu(formdata).then((res) => {
              resolve(`http://toutiao.longxiaokj.com/` + res.data.key);
            });
          });
        });
      });

      let imageSrc = await Promise.all(task);
      return imageSrc;
      // 上传多图
      // @return  上传到服务器的图片路径
    },
  },
  modules: {},
});
